package com.shijie.service;

import com.shijie.component.ErpUserService;
import com.shijie.core.AbstractService;
import com.shijie.core.ServiceException;
import com.shijie.domain.entity.*;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.domain.enums.EnumInterface.Status;
import com.shijie.mapper.*;
import com.shijie.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class ProductsService extends AbstractService<Products> {

    @Resource
    private ProductsMapper productsMapper;
    @Resource
    private SkusMapper skusMapper;
    @Resource
    private AttachmentsMapper attachmentsMapper;
    @Resource
    private BrandsMapper brandsMapper;
    @Autowired
    private ErpUserService erpUserService;
    @Autowired
    private ActivityProductsMapper activityProductsMapper;
    @Autowired
    private RecommendsMapper recommendsMapper;
    @Autowired
    private PictureSynthesisService pictureSynthesisService;

    public List<Products> selectProducts(Integer brandId, Integer activityId, Integer categoryId, String q) {
        return productsMapper.selectProducts(brandId, activityId, categoryId, q,null,null);
    }

    public List<Products> searchProducts(String q,Integer status,Integer tradeType) {
        Admins admin = erpUserService.getAdmin();
        Integer brandId = null;
        if (admin != null && admin.getBrandId() != null) {
            brandId = admin.getBrandId();
        }
        return productsMapper.selectProducts(brandId, null, null, q,status,tradeType);
    }

    public void save(Products products) {
        this.setOther(products);
        if (products.getId() == null) {
            products.setCreateBy(erpUserService.getUserName());
            products.setCreateTime(DateTime.now().toDate());
            productsMapper.insert(products);
            if (products.getSkus().size() > 0) {
                products.getSkus().forEach(c -> {
                    c.setProductId(products.getId());
                });
                skusMapper.insertList(products.getSkus());
            }
            if (products.getPictrues().size() > 0) {
                products.getPictrues().forEach(
                        c -> {
                            c.setEntityType(EnumInterface.EntityType.PRODUCT
                                    .ordinal());
                            c.setEntityId(products.getId());
                            c.setCreateBy(erpUserService.getUserName());
                            c.setCreateTime(DateTime.now().toDate());
                        });
                int sort = 1;
                for (Attachments a : products.getPictrues()) {
                    a.setSorts(sort++);
                }
                attachmentsMapper.insertList(products.getPictrues());
            }
        } else {
            products.setUpdateBy(erpUserService.getUserName());
            products.setUpdateTime(DateTime.now().toDate());
            productsMapper.updateByPrimaryKey(products);
            Condition condition = new Condition(Skus.class);
            condition.createCriteria()
                    .andEqualTo("productId", products.getId());
            skusMapper.deleteByCondition(condition);
            if (products.getSkus().size() > 0) {
                products.getSkus().forEach(c -> {
                    c.setProductId(products.getId());
                });
                skusMapper.insertList(products.getSkus());
            }

            Condition conditionx = new Condition(Attachments.class);
            conditionx
                    .createCriteria()
                    .andEqualTo("entityId", products.getId())
                    .andEqualTo("entityType",
                            EnumInterface.EntityType.PRODUCT.ordinal());
            attachmentsMapper.deleteByCondition(conditionx);
            if (products.getPictrues().size() > 0) {
                products.getPictrues().forEach(
                        c -> {
                            c.setEntityType(EnumInterface.EntityType.PRODUCT
                                    .ordinal());
                            c.setEntityId(products.getId());
                            c.setStatus(Status.VALID.ordinal());
                            c.setCreateBy(erpUserService.getUserName());
                            c.setCreateTime(DateTime.now().toDate());
                        });
                int sort = 1;
                for (Attachments a : products.getPictrues()) {
                    a.setSorts(sort++);
                }
                attachmentsMapper.insertList(products.getPictrues());
            }
        }
        pictureSynthesisService.syntherisPicture(products);
    }

    private void setOther(Products products) {
        Brands brand = brandsMapper.selectByPrimaryKey(products.getBrandId());
        products.setBrandName(brand.getName());
        if (products.getSkus() != null) {
            Set<String> colors = new HashSet<>();
            Set<String> sises = new HashSet<>();
            for (Skus sku : products.getSkus()) {
                if (!StringUtils.isEmpty(sku.getColor())) {
                    colors.add(sku.getColor());
                }
                if (!StringUtils.isEmpty(sku.getSize())) {
                    sises.add(sku.getSize());
                }
            }
            products.setColors(JsonUtil.toJson(colors));
            products.setSizes(JsonUtil.toJson(sises));
        }
    }

    public Products selectById(Integer id) {
        Products product = productsMapper.selectByPrimaryKey(id);

        Condition conditionx = new Condition(Attachments.class);
        conditionx
                .createCriteria()
                .andEqualTo("entityId", id)
                .andEqualTo("entityType",
                        EnumInterface.EntityType.PRODUCT.ordinal());
        List<Attachments> pictrues = attachmentsMapper
                .selectByCondition(conditionx);
        product.setPictrues(pictrues);

        Condition condition = new Condition(Skus.class);
        condition.createCriteria().andEqualTo("productId", id);
        List<Skus> skus = skusMapper.selectByCondition(condition);

        product.setSkus(skus);

        return product;
    }

    public void delete(Integer id) {
        // 未推荐，未优惠活动
        ActivityProducts ap = new ActivityProducts();
        ap.setProductId(id);
        if (activityProductsMapper.selectCount(ap) > 0) {
            throw new ServiceException("该产品已加入专题活动，请先删除优惠活动");
        }
        Recommends r = new Recommends();
        r.setEntityId(id);
        r.setEntityType(0);
        if (recommendsMapper.selectCount(r) > 0) {
            throw new ServiceException("该产品已加入推荐活动，请先删除推荐信息");
        }
        Products p = new Products();
        p.setId(id);
        p.setStatus(String.valueOf(Status.CANCEL.ordinal()));
        productsMapper.updateByPrimaryKeySelective(p);
    }

}
